package com.coding.config;

import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author Cynicism
 * @version 1.0
 * @project code-starter
 * @description
 * @date 2024/5/29 15:54:12
 */
@Configuration
public class MyRedis {
    @Bean
    public RedisTemplate<String, Object> MyRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        FastJsonRedisSerializer<Object> objectFastJsonRedisSerializer = new FastJsonRedisSerializer<Object>(Object.class);
//        GenericJackson2JsonRedisSerializer jsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        Jackson2JsonRedisSerializer<Object> jsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        // 配置 ObjectMapper
        ObjectMapper objectMapper = new ObjectMapper();
        jsonRedisSerializer.setObjectMapper(objectMapper);

        // 设置其他的k-v的默认的序列化
//        template.setDefaultSerializer(jsonRedisSerializer);
        //单独设置k的序列化
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(objectFastJsonRedisSerializer);


        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置value的序列化器
        template.setValueSerializer(objectFastJsonRedisSerializer);
        template.setHashValueSerializer(jsonRedisSerializer);

        template.afterPropertiesSet();



        return template;
    }
}
